package com.acme.team02.chat.server.connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;

import com.acme.team02.chat.server.ChatServer;

public class Connect implements Runnable {
	private Socket client;

	private OnMessageReceivedListener onMessageReceivedListener;
	
	BufferedReader in;
	PrintWriter out;

	Connect(Socket client, OnMessageReceivedListener listener) {
		this.client = client;
		this.onMessageReceivedListener = listener;
		
		try {
			in = new BufferedReader(new InputStreamReader(
					client.getInputStream()));
			out = new PrintWriter(client.getOutputStream(), true);
		} catch (IOException e) {
//			e.printStackTrace();
			ChatServer.logger.log(Level.WARNING, e + "");
			disconnect();
		}
		
		

	}

	@Override
	public void run() {
		try {
			while(true){
				getMessage(in);
			}
		} catch (IOException ioe) {
//			System.out.println("Exception on get message. Disconnecting client");
			ChatServer.logger.log(Level.WARNING, "Exception on get message. Disconnecting client" + ioe + "");
			disconnect();
		}
	}

	private void getMessage(BufferedReader in) throws IOException {
		String fromServer;

		while ((fromServer = in.readLine()) != null) {
			System.out.println("Client: " + fromServer);
			onMessageReceivedListener.onMessageReceived(this, fromServer);
		}
	}

	/**
	 * 
	 * Send string to client
	 * @param message string to send
	 */
	public void sendMessage(String message) {
			out.println(message);
	}
	
	private void disconnect(){
			try {
				if(in!=null) in.close();
				if(out!=null) out.close();
				if(client!=null) client.close();
			} catch (IOException e) {
				e.printStackTrace();
				ChatServer.logger.log(Level.WARNING, e + "");
			}

	}

	public interface OnMessageReceivedListener {
		void onMessageReceived(Connect connect, String message);
	}
}
